package com.enation.app.javashop.consumer.shop.wms;

import com.enation.app.javashop.consumer.core.event.*;
import com.enation.app.javashop.core.aftersale.model.dos.ClaimsDO;
import com.enation.app.javashop.core.aftersale.model.dos.RefundDO;
import com.enation.app.javashop.core.aftersale.model.enums.ClaimsStatusEnum;
import com.enation.app.javashop.core.aftersale.model.enums.ClaimsTypeEnum;
import com.enation.app.javashop.core.aftersale.model.enums.RefundStatusEnum;
import com.enation.app.javashop.core.aftersale.model.vo.ClaimsChangeMsg;
import com.enation.app.javashop.core.base.message.OrderStatusChangeMsg;
import com.enation.app.javashop.core.base.message.RefundChangeMsg;
import com.enation.app.javashop.core.member.model.enums.AuditEnum;
import com.enation.app.javashop.core.promotion.pintuan.model.PintuanOrderStatus;
import com.enation.app.javashop.core.shop.model.dto.FixTimeSection;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.core.shop.service.impl.OrderReceiveTimeManager;
import com.enation.app.javashop.core.trade.cart.model.dos.OrderPermission;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.core.trade.order.model.enums.OrderStatusEnum;
import com.enation.app.javashop.core.trade.order.model.enums.OrderTypeEnum;
import com.enation.app.javashop.core.trade.order.model.enums.ShipTypeEnum;
import com.enation.app.javashop.core.trade.order.model.vo.DeliveryVO;
import com.enation.app.javashop.core.trade.order.service.OrderMemberManager;
import com.enation.app.javashop.core.trade.order.service.OrderOperateManager;
import com.enation.app.javashop.core.trade.order.service.OrderProfitManager;
import com.enation.app.javashop.core.trade.order.service.OrderQueryManager;
import com.enation.app.javashop.core.trade.sdk.model.OrderDetailDTO;
import com.enation.app.javashop.core.wms.model.vo.WmsOrderChangeMsg;
import com.enation.app.javashop.core.wms.service.WmsOrderManager;
import com.enation.app.javashop.framework.database.DaoSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  出库单管理
 */
@Service
public class WmsOrderConsumer implements OrderStatusChangeEvent, RefundStatusChangeEvent, ClaimsChangeEvent, WmsOrderMessageEvent, PintuanSuccessEvent {

    @Autowired
    private WmsOrderManager wmsOrderManager;

    @Autowired
    private OrderOperateManager orderOperateManager;


    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport tradeDaoSupport;

    @Autowired
    private ShopManager shopManager;

    @Autowired
    private OrderReceiveTimeManager orderReceiveTimeManager;


    protected final Log logger = LogFactory.getLog(getClass());

    @Override
    public void orderChange(OrderStatusChangeMsg orderMessage) {
        logger.info("社团订单支付-准备出库："+orderMessage.toString());
        if(orderMessage.getNewStatus().equals(OrderStatusEnum.PAID_OFF)){
            //获取订单信息
            OrderDO order = orderMessage.getOrderDO();
            if (!order.getOrderType().equals(OrderTypeEnum.shetuan.name())) {
                return;
            }
            wmsOrderManager.acceptOrder(order);
        }
        if(orderMessage.getNewStatus().equals(OrderStatusEnum.SHIPPED)){
            //获取订单信息
            OrderDO order = orderMessage.getOrderDO();

            wmsOrderManager.orderSended(order);
        }
    }

    @Override
    public void refund(RefundChangeMsg refundChangeMsg) {
        if(refundChangeMsg.getRefundStatusEnum().equals(RefundStatusEnum.PASS)){
            logger.info("订单售后-取消出库单："+refundChangeMsg.toString());
            //获取退款单信息
            RefundDO refundDO = refundChangeMsg.getRefund();

            wmsOrderManager.cancelOrder(refundDO);
        }
    }

    @Override
    public void claimsChange(ClaimsChangeMsg claimsChangeMsg) {
        if(claimsChangeMsg.getAuditEnum().equals(ClaimsStatusEnum.AUDIT_SUCCESS.value())){
            logger.info("理赔审核通过-准备出库："+claimsChangeMsg.toString());
            List<ClaimsDO> claimsDOList = claimsChangeMsg.getClaimsDOList();
            for (ClaimsDO claimsDO : claimsDOList) {
                if(claimsDO.getClaimType().equals(ClaimsTypeEnum.COMPENSATION_GOODS.value()) ||claimsDO.getClaimType().equals(ClaimsTypeEnum.FREE_GIFT.value())  ){
                    wmsOrderManager.acceptClaims(claimsDO);
                }
            }
        }
        if(claimsChangeMsg.getAuditEnum().equals(ClaimsStatusEnum.CANCELLED.value())){
            logger.info("理赔审核撤销-取消出库："+claimsChangeMsg.toString());
            List<ClaimsDO> claimsDOList = claimsChangeMsg.getClaimsDOList();
            for (ClaimsDO claimsDO : claimsDOList) {
                if(claimsDO.getClaimType().equals(ClaimsTypeEnum.COMPENSATION_GOODS.value()) ||claimsDO.getClaimType().equals(ClaimsTypeEnum.FREE_GIFT.value())  ){
                    wmsOrderManager.cancelClaims(claimsDO);
                }
            }
        }
    }

    @Override
    public void change(WmsOrderChangeMsg wmsOrderChangeMsg) {
        List<String> orderSnList = wmsOrderChangeMsg.getOrderSnList();
        for (String orderSn : orderSnList) {
            DeliveryVO delivery = new DeliveryVO();
            delivery.setOrderSn(orderSn);
            delivery.setDeliveryNo("-");
            delivery.setLogiName("自提配送");
            delivery.setLogiId(0);

            try {
                orderOperateManager.ship(delivery, OrderPermission.client);
            } catch (Exception e) {
                logger.error("【出库通知订单发货失败】："+orderSn+e.getMessage());
            }
        }
    }

    @Override
    public void success(Integer pintuanOrderId) {
        logger.info("社区拼单支付-准备出库："+pintuanOrderId);
        //拼团主id查询相关的拼团订单，循环给每个人发送消息
        String sql = "select o.* from es_pintuan_child_order pc inner join es_order o on pc.order_sn = o.sn where pc.order_id = ? and pc.order_status=? ";
        List<OrderDO> orders = this.tradeDaoSupport.queryForList(sql, OrderDO.class, pintuanOrderId, PintuanOrderStatus.formed.name());

        // 重新计算出库时间 因为存在跨天的拼团活动 拼团的发货时间在成团之日的次日
        // FixTimeSection timeSection=orderReceiveTimeManager.getReceiveTimeBySeller(orders.get(0).getSellerId(),null);
        for (OrderDO order : orders) {
            // order.setReceiveTime(timeSection.getReceiveTimeStamp());
            // order.setReceiveTimeType(timeSection.getReceiveTimeType());
            // 拼团订单进入出库的条件：店铺Id属于社区团购店铺
            if(shopManager.checkIsShetuan(order.getSellerId())){
                wmsOrderManager.acceptOrder(order);
            }
        }
    }
}
